require('dotenv').config(); // 加载 .env 文件中的环境变量
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const morgan = require('morgan'); // HTTP 请求日志

// --- 显式导入 Mongoose 模型 --- (确保在路由之前导入)
require('./models/user.model');
require('./models/video.model');
require('./models/post.model');
require('./models/comment.model');
require('./models/category.model');
require('./models/topic.model');
require('./models/setting.model');
// --- 模型导入结束 ---

// 路由
const authRoutes = require('./routes/auth.routes');
const userRoutes = require('./routes/user.routes');
const videoRoutes = require('./routes/video.routes');
const commentRoutes = require('./routes/comment.routes');
const categoryRoutes = require('./routes/category.routes');
const postRoutes = require('./routes/post.routes'); // 假设有帖子路由
const topicRoutes = require('./routes/topic.routes'); // 添加话题路由
const adminRoutes = require('./routes/admin.routes'); // 引入 admin 路由
const settingRoutes = require('./routes/setting.routes'); // Assuming setting routes exist

const app = express();
const PORT = process.env.PORT || 3000; // 
const MONGODB_URI = process.env.MONGODB_URI;

// --- 数据库连接 ---
mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
.then(() => console.log('MongoDB 连接成功'))
.catch(err => console.error('MongoDB 连接失败:', err));

// --- 中间件 ---
// app.use(cors()); // 允许跨域请求 - 旧代码
app.use(cors({ origin: process.env.CORS_ORIGIN || '*' })); // 使用环境变量配置 CORS
app.use(express.json()); // 解析 JSON 请求体
app.use(express.urlencoded({ extended: true })); // 解析 URL 编码的请求体
app.use(morgan('dev')); // 开发环境日志

// 创建必要的上传目录
const uploadDirs = [
  path.join(__dirname, '../uploads'),
  path.join(__dirname, '../uploads/posts'),
  path.join(__dirname, '../uploads/avatars'),
  path.join(__dirname, '../uploads/thumbnails'),
  path.join(__dirname, '../uploads/videos')
];

uploadDirs.forEach(dir => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
});

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

console.log('--- Registering API Routes ---'); // 添加日志

// --- 路由 ---
// API 路由
app.use('/api/auth', authRoutes);
console.log('Registered /api/auth'); // 添加日志
app.use('/api/users', userRoutes);
console.log('Registered /api/users'); // 修正日志信息，之前是'/api/user'
app.use('/api/videos', videoRoutes);
console.log('Registered /api/videos'); // 添加日志
app.use('/api/comments', commentRoutes);
console.log('Registered /api/comments'); // 添加日志
app.use('/api/categories', categoryRoutes);
console.log('Registered /api/categories'); // 添加日志
app.use('/api/posts', postRoutes); // 注册帖子路由
console.log('Registered /api/posts'); // 添加日志
app.use('/api/topics', topicRoutes); // 注册话题路由
console.log('Registered /api/topics'); // 添加日志
app.use('/api/admin', adminRoutes); // 注册 admin 路由
console.log('Registered /api/admin'); // 添加日志
app.use('/api/settings', settingRoutes);   // Mount setting routes
console.log('Registered /api/settings'); // 添加日志

console.log('--- API Routes Registered ---'); // 添加日志

// Basic route for testing
app.get('/', (req, res) => {
  res.send('Backend server is running!');
});

// 添加资源回退中间件
const { resourceFallback } = require('./middlewares/resource.middleware');

// 为常见静态资源提供默认回退
app.use('/src/assets/default-avatar.svg', resourceFallback('/frontend/public/default-avatar.png'));
app.use('/uploads/thumbnails', resourceFallback('/frontend/public/default-thumbnail.png'));
app.use('/uploads/avatars', resourceFallback('/frontend/public/default-avatar.png'));

// --- Error Handling ---
// 在所有路由之后添加错误处理中间件
const errorHandler = require('./middlewares/error.middleware');

// 404处理 - 放在所有路由之后，错误处理之前
app.use((req, res, next) => {
  console.error(`404 - 请求未找到: ${req.method} ${req.path}`); // 添加详细日志
  res.status(404).json({ 
    error: '请求的资源不存在', 
    path: req.path,
    method: req.method,
    timestamp: new Date().toISOString()
  });
});

// 全局错误处理中间件 - 放在所有中间件的最后
app.use(errorHandler);

// --- 启动服务器 ---
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

module.exports = app;